package com.example.authservice.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.authservice.dto.LoginRequest;
import com.example.commonservice.Common.Result;
import com.example.authservice.entity.User;
import com.example.authservice.service.UserAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("auth")
public class AuthController {

    @Autowired
    private UserAuthService authService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody User user) {
        //create_time
        user.setCreateTime(LocalDateTime.now());
        boolean success = authService.register(user);
        return success ? Result.success("注册成功") : Result.error("用户名已存在，注册失败");
    }

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginRequest request) {
        User user = authService.login(request.getUsername(), request.getPassword());
        if (user != null) {
            StpUtil.login(user.getId());
            String token = StpUtil.getTokenValue();

            // 打印token和存储的key
            System.out.println("生成的Token: " + token);
            String tokenKey = "login-token:" + token;
            System.out.println("存储到Redis的Key: " + tokenKey);

            redisTemplate.opsForValue().set(
                    tokenKey,
                    JSON.toJSONString(user),
                    30,
                    TimeUnit.MINUTES
            );

            Map<String, Object> data = new HashMap<>();
            data.put("tokenInfo", token);
            data.put("user", user);
            return Result.success("登录成功", data);
        }
        return Result.error("用户名或密码错误");
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        StpUtil.logout();
        return Result.success("退出成功");
    }

    /**
     * 检查登录状态
     */
    @GetMapping("/checkLogin")
    public Result<Boolean> checkLogin() {
        return Result.success(StpUtil.isLogin());
    }

    /**
     * 删除用户（管理员）
     */
    @PostMapping("/delete")
    public Result<String> deleteUser(@RequestParam Long id) {
        boolean success = authService.removeById(id);
        return success ? Result.success("用户删除成功") : Result.error("用户不存在，删除失败");
    }

    /**
     * 更新用户信息（管理员）
     */
    @PostMapping("/update")
    public Result<String> updateUser(@RequestBody User user) {
        boolean success = authService.updateById(user);
        return success ? Result.success("用户更新成功") : Result.error("用户不存在，更新失败");
    }

    /**
     * 条件分页查询用户（管理员）
     */
    @GetMapping("/list")
    public Result<IPage<User>> listUsers(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) Integer role) {

        Map<String, Object> params = new HashMap<>();
        params.put("username", username);
        params.put("role", role);
        return Result.success(authService.pageUsers(current, size, params));
    }
}
